<?php

/**
 * This is the model class for table "r_menu".
 *
 * The followings are the available columns in table 'r_menu':
 * @property integer $id
 * @property string $name
 * @property string $lable
 * @property integer $parentid
 * @property string $m
 * @property string $c
 * @property string $a
 * @property string $data
 * @property integer $listorder
 * @property string $display
 */
class Menus extends ActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @return Menus the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'r_menu';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('parentid, listorder', 'numerical', 'integerOnly'=>true),
            array('name', 'length', 'max'=>40),
            array('lable', 'length', 'max'=>255),
            array('m, c, a', 'length', 'max'=>20),
            array('data', 'length', 'max'=>100),
            array('display', 'length', 'max'=>1),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, name, lable, parentid, m, c, a, data, listorder, display', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'name' => '名称',
            'lable' => '显示名称',
            'parentid' => '上级菜单',
            'm' => '模块',
            'c' => '控制器',
            'a' => '动作',
            'data' => 'Data',
            'listorder' => 'Listorder',
            'display' => 'Display',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('name',$this->name,true);
        $criteria->compare('lable',$this->lable,true);
        $criteria->compare('parentid',$this->parentid);
        $criteria->compare('m',$this->m,true);
        $criteria->compare('c',$this->c,true);
        $criteria->compare('a',$this->a,true);
        $criteria->compare('data',$this->data,true);
        $criteria->compare('listorder',$this->listorder);
        $criteria->compare('display',$this->display,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    //
    public function getMenuInfo($rules)
    {
        $menu_array = array();

        foreach($rules as $rule)
        {
            $row = $this->getInfoByMVC($rule);

            //过滤不显示的菜单
            if( (Yii::app()->user->getId()!=1) && ($row['display']==0)){
                continue;
            }

            if(!empty($row) && $row['parentid']>0 ){
                $parentid = $row['parentid'];
                if( empty($menu_array[$parentid]) ){
                    $menu_array[$parentid] = $this->getInfoById($parentid);
                }
                $menu_array[$parentid]['sub_menu'][$row['id']] = $row;
            }
        }

        return $menu_array;
    }

    public function getInfoByMVC($rule)
    {
        $ruleArr = explode('.', $rule);
        //echo $rule.'--';
        if( empty($ruleArr[0]) || empty($ruleArr[1]) ){
            return array();
        }

        $sql = "SELECT * FROM " . $this->tableName() . " WHERE m='" . $ruleArr[0] . "' AND c='" . $ruleArr[1] . "'";
        return $this->dbConnection->createCommand($sql)->queryRow();
    }

    public function getInfoById($id)
    {
        $query = "SELECT * FROM " . $this->tableName() . " WHERE id=" . $id;
        return $this->dbConnection->createCommand($query)->queryRow();
    }

    public function getChildMenus($pid)
    {
        $query = "SELECT * FROM " . $this->tableName() . " WHERE parentid=" . $pid . " AND display=1 ORDER BY listorder ASC";
        return $this->dbConnection->createCommand($query)->queryAll();
    }

    public function getAllMenus()
    {
        $menu_array = array();

        $query = "SELECT * FROM " . $this->tableName() . " ORDER BY listorder ASC";
        $rows = $this->dbConnection->createCommand($query)->queryAll();

        foreach($rows as $k=>$row)
        {
            $parentid = $row['parentid'];
            if($parentid==0){
                $menu_array[$row['id']] = $row;
                unset($rows[$k]);
            }
        }

        foreach($rows as $row)
        {
            $parentid = $row['parentid'];
            $menu_array[$parentid]['sub_menu'][$row['id']] = $row;
        }

        return $menu_array;
    }

    //更新排序
    public function updateSort($id,$sort)
    {
        if($id<=0 || $sort<=0){
            return false;
        }

        $sql = "UPDATE " . $this->tableName() . " SET listorder=" . $sort . " WHERE id=" . $id . " AND listorder!=" . $sort;
        $this->dbConnection->createCommand($sql)->execute();
    }

    public function doCreate($data)
    {
        if( empty($data) ){
            return false;
        }

        $this->attributes = $data;
        $transaction = $this->dbConnection->beginTransaction();
        try
        {
            if( !empty($this->m) && !empty($this->c) && !empty($this->a) )
            {
                if(!$this->save()){
                    throw new Exception('保存菜单时出错');
                }

                // Create the item
                $name = $this->m . '.' . $this->c . '.*';
                $sql = "INSERT INTO r_auth_item(`name`,`type`,`description`) VALUES('{$name}',1,'{$this->lable}')";
                $this->dbConnection->createCommand($sql)->execute();

                //更新
                $this->updateByPk($this->id, array('listorder'=>$this->id) );

                $transaction->commit();

                return true;
            }
        }
        catch(Exception $e)
        {
            $this->addError('menu_lable', $e->getMessage());
            $transaction->rollBack();
        }
    }

}